﻿using Mengsk.ProxyDelivery.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Mengsk.ProxyDelivery.App.Extenstions;
using Mengsk.ProxyDelivery.Domain;
using System.Collections.ObjectModel;
using Mengsk.ProxyDelivery.App.Service;
namespace Mengsk.ProxyDelivery.App.UI.Order
{
    /// <summary>
    /// OrderReturnBackUserControl.xaml 的交互逻辑
    /// </summary>
    public partial class OrderReturnBackUserControl : UserControl, IPlugin
    {
        private bool myLoaded = false;
        private OrderChangeService orderChangeService = ServiceContainer.GetService<OrderChangeService>();
        private System.Collections.ObjectModel.ObservableCollection<OrderChangeOutViewModel> ups = new System.Collections.ObjectModel.ObservableCollection<OrderChangeOutViewModel>();
        private System.Collections.ObjectModel.ObservableCollection<OrderChangeOutViewModel> downs = new System.Collections.ObjectModel.ObservableCollection<OrderChangeOutViewModel>();
        public string Title
        {
            get { return "退货回单"; }
        }

        public Control UIControl
        {
            get { return this; }
        }

        public OrderReturnBackUserControl()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (this.myLoaded)
            {
                return;
            }
            this.myLoaded = true;
            this.dpStart.Value = DateTime.Now.AddDays(-2);
            this.dpEnd.Value = DateTime.Now;
            this.cbbStates.Bind<OrderChangeState>();
            this.ups.CollectionChanged += CollectionChanged;
            this.downs.CollectionChanged += CollectionChanged;
            this.dgvAll.ItemsSource = this.ups;
            this.dgvDown.ItemsSource = this.downs;
        }

        void CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            this.tbCount.Text = string.Format("总数:{0},上面:{1}，下面:{2}", this.ups.Count + this.downs.Count, this.ups.Count, this.downs.Count);
        }

        private void btnQuery_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (this.dpStart.Value == null)
                {
                    throw new Exception("选择开始时间");
                }

                DateTime start = this.dpStart.Value.Value;
                DateTime end = this.dpEnd.Value == null ? DateTime.Now : this.dpEnd.Value.Value;

                if (end.Subtract(start).TotalDays > 5)
                {
                    throw new Exception("查询时间不能超过5天");
                }

                this.ups.Clear();
                this.downs.Clear();

                OrderChangeState state = this.cbbStates.GetSelectedEnum<OrderChangeState>();
                var datas = this.orderChangeService.GetByAll(0, 0, 0, "", "", "", 4, start, end, (int)(state), 0, "", 0, 0);
                foreach (var item in datas.Datas.Select(obj => new OrderChangeOutViewModel { OrderChange = obj }))
                {
                    this.ups.Add(item);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        private void btnClearAll_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("是否清空", "请确认", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
            {
                return;
            }
            this.ups.Clear();
            this.downs.Clear();
        }

        private void btnClearDown_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("是否清空", "请确认", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
            {
                return;
            }
            this.downs.Clear();
        }

        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OrderChangeOutViewModel orderBack = (e.Source as Hyperlink).DataContext as OrderChangeOutViewModel;
                if (orderBack == null)
                {
                    return;
                }
                this.ups.Remove(orderBack);
                this.downs.Remove(orderBack);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        private void btnMarkWaitToRefund_Click(object sender, RoutedEventArgs e)
        {
            this.UpdateState(this.ups, OrderChangeState.WaitRefund);
        }


        private void btnMarkFail_Click(object sender, RoutedEventArgs e)
        {
            this.UpdateState(this.downs, OrderChangeState.ToVendorFail);
        }

        private void UpdateState(ObservableCollection<OrderChangeOutViewModel> items, OrderChangeState state)
        {
            try
            {
                if (items.Count < 1)
                {
                    MessageBox.Show("没有需要操作的退货");
                    return;
                }

                foreach (var item in items)
                {
                    try
                    {
                        if (state == OrderChangeState.ToVendorFail)
                        {
                            if (string.IsNullOrWhiteSpace(item.OrderChange.SystemComment))
                            {
                                throw new Exception("退货必须输入描述");
                            }
                            this.orderChangeService.MarkToVendorFail(item.OrderChange.Id, item.OrderChange.SystemComment);
                        }
                        else if (state == OrderChangeState.WaitRefund)
                        {
                            this.orderChangeService.MarkWaitRefund(item.OrderChange.Id);
                        }
                        else
                        {
                            throw new Exception("要改变的订单状态不正确");
                        }
                        item.State = "已处理成功";
                        item.OrderChange.State = state;
                    }
                    catch (Exception ex)
                    {
                        item.State = ex.Message;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                this.dgvAll.Items.Refresh();
                this.dgvDown.Items.Refresh();
            }
        }

        private void tbOrderChangeId_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Enter)
            {
                return;
            }
            try
            {
                string strid = this.tbOrderChangeId.Text.Trim();
                if (String.IsNullOrWhiteSpace(strid))
                {
                    return;
                }
                int id = int.Parse(strid);

                var item = this.downs.FirstOrDefault(obj => obj.OrderChange.Id == id);
                if (item != null)
                {
                    Speaker.Speak("已扫描");
                    return;
                }

                item = this.ups.FirstOrDefault(obj => obj.OrderChange.Id == id);
                if (item == null)
                {
                    Speaker.Speak("不存在");
                    return;
                }

                this.ups.Remove(item);
                this.downs.Add(item);
                Speaker.Speak("已接受");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                e.Handled = true;
                this.tbOrderChangeId.Text = "";
            }
        }
    }
}
